import React, { Component } from "react";
import SockJS from "sockjs-client";
import Stomp from "stompjs";

class Dashboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      stompClient: null,
      data: "abc",
    };
    this.handleOnConnected = this.handleOnConnected.bind(this);
    this.handleOnMessageReceived = this.handleOnMessageReceived.bind(this);
  }

  UNSAFE_componentWillMount() {
    let socket = new SockJS("http://localhost:8080/ws");
    this.setState({ stompClient: Stomp.over(socket) });
  }

  componentWillUnmount(){
    const { stompClient } = this.state;
    stompClient.unsubscribe("/topic/public")
    stompClient.disconnect()
  }

  componentDidMount() {
    const { stompClient } = this.state;
    stompClient.connect({}, this.handleOnConnected, this.handleOnError);
  }

  handleOnConnected() {
    // Subscribe to the Public Topic
    const { stompClient } = this.state;
    stompClient.subscribe("/topic/public", this.handleOnMessageReceived);
  }

  handleOnMessageReceived(payload) {
    this.setState({ data: payload.body });
  }

  handleOnError(error) {
    console.log(JSON.stringify(error));
  }

  render() {
    return (
      <div>
        Count: <strong>{this.state.data}</strong>
      </div>
    );
  }
}

export default (props) => (
  <Dashboard {...props} key={props.location.pathname} />
);
